﻿@*******************************************************************************************************
//  Documents.cshtml - Gbtc
//
//  Copyright © 2016, Grid Protection Alliance.  All Rights Reserved.
//
//  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
//  the NOTICE file distributed with this work for additional information regarding copyright ownership.
//  The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this
//  file except in compliance with the License. You may obtain a copy of the License at:
//
//      http://opensource.org/licenses/MIT
//
//  Unless agreed to in writing, the subject software distributed under the License is distributed on an
//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
//  License for the specific language governing permissions and limitations.
//
//  Code Modification History:
//  ----------------------------------------------------------------------------------------------------
//  04/09/2016 - Ritchie Carroll
//       Generated original version of source code.
//
//*****************************************************************************************************@
@using System.Collections.Specialized
@using GSF.Web
@using GSF.Web.Model

@using PQDashboard.Model
@section StyleSheets {
    @Styles.Render("~/css.bundle/fileinput")
}
@model PQDashboard.Model.AppModel
@{
    DataContext dataContext = Model.DataContext;
    NameValueCollection parameters = Request.QueryString;
    string sourceTable = parameters["SourceTable"];
    string sourceField = parameters["SourceField"];
    bool hideButton = bool.Parse(parameters["HideButton"] ?? "false");
    string titleStart = parameters["titleStart"] ?? "Manage";

    int sourceID = int.Parse(parameters["SourceID"] ?? "0");

    if (string.IsNullOrEmpty(sourceTable) || string.IsNullOrEmpty(sourceField) || sourceID < 1)
    {
        throw new ArgumentException("Expected source document page parameters are missing or invalid");
    }

    ViewBag.CustomTitle = titleStart + " \"" + parameters["Name"] + "\" " + sourceTable + " Documents";
    ViewBag.AddNewEditTitle = "Documents for \"" + parameters["Name"] + "\" " + sourceTable;
    ViewBag.PageHasMenu = false;
    ViewBag.HeaderColumns = new[]
{   //    { "Field", "Label", "Classes" }
        new[] { "Filename", "File Name", "text-left" },
        new[] { null, "Document Type", "text-center" }
    };

    ViewBag.BodyRows = BodyRows(sourceTable).ToString();
    ViewBag.AddNewEditDialog = AddNewEditDialog().ToString();
    ViewBag.HideAddNewButton = hideButton;
    ViewBag.CanEdit = false;
    ViewBag.HideUnauthorizedControls = true;
}
@helper BodyRows(string sourceTable)
{
    <td width="80%" class="text-left table-cell-hard-wrap"><a data-bind="attr:{href: '@Html.Raw(Url.Content($"~/FileDownloadHandler.ashx?SourceTable={sourceTable.UrlEncode()}Document&DocumentID="))' + DocumentID}" target="_blank"><div data-bind="text: $($element.parentElement.parentElement).truncateToWidth(Filename, 2)"></div></a></td>
    <td width="15%" class="text-center valign-middle" data-bind="text: lookupFileTypeValue(DocumentTypeKey)"></td>
    <td width="5%" class="text-center valign-middle" nowrap>
        <button type="button" class="btn btn-xs" data-bind="click: $parent.removePageRecord, enable: $parent.dataHubIsConnected"><span class="glyphicon glyphicon-remove"></span></button>
    </td>
}
@helper AddNewEditDialog()
{
    <div class="col-md-12">
        <input id="uploadFiles" name="uploadFiles[]" type="file" multiple class="file-loading">
    </div>
}
@Html.Partial("PagedViewModel")

@section Scripts {
    @Scripts.Render("~/js.bundle/fileinput")
    <script>
        "use strict";
        @Html.Raw(Model.RenderViewModelConfiguration<DocumentDetail>(ViewBag, "Filename", $"'{sourceTable}'", sourceID))
        @Html.Raw(Model.RenderValueListClientLookupFunction("fileType", lookupFunctionName: "lookupFileTypeValue"))

        $(function () {

            $("#addNewEditDialog").on("shown.bs.modal", function () {
                // On add/edit dialog shown, disable data-dismiss buttons on parent pop-up
                const dismissButtons = $("#manageDocumentsDialog", window.parent.document).find("button[data-dismiss]");
                dismissButtons.prop("disabled", true);
                dismissButtons.invisible();

                $("#uploadFiles").fileinput({
                    uploadUrl: "@Html.Raw(Url.Content($"~/FileUploadHandler.ashx?SourceTable={sourceTable.UrlEncode()}Document&SourceField={sourceField.UrlEncode()}&SourceID={sourceID}"))",
                    uploadAsync: true,
                    showUpload: true,
                    showRemove: false,
                    minFileCount: 1,
                    maxFileCount: 12
                });

                // Update cancel button to say close since work to upload files will already have been handled
                $("#saveRecordButton").hide();
                $("#cancelRecordButton").text("Close");
            });

            $("#addNewEditDialog").on("hidden.bs.modal", function () {
                // On add/edit dialog hidden, re-enable data-dismiss buttons on parent pop-up
                const dismissButtons = $("#manageDocumentsDialog", window.parent.document).find("button[data-dismiss]");
                dismissButtons.visible();
                dismissButtons.prop("disabled", false);

                // Refresh view model after new uploads
                viewModel.initialize();
            });
        });
    </script>
}